import { createScopedThreejs } from 'threejs-miniprogram'

Page({
  data: {
    diceValue1: null,
    diceValue2: null, 
    diceSum: null,
    isRolling: false,
    // 八卦名称数组 (1-8对应)
    baguaNames: ['乾', '坤', '震', '艮', '离', '坎', '兑', '巽'],
    // 八卦符号表示
    baguaSymbols: ['☰', '☷', '☳', '☶', '☲', '☵', '☱', '☴'],
    fullGuaName: ''
  },
  
  onLoad: function() {
    // 确保小程序已完成初始化
    console.log('页面加载中...')
  },
  
  onReady() {
    console.log('页面准备好了，准备初始化Canvas')
    // 需要使用正确的选择器，确保页面已渲染
    setTimeout(() => {
      this.initThree()
    }, 300) // 增加延迟时间
  },
  
  initThree() {
    console.log('开始初始化Three.js')
    
    // 使用不同的方式获取canvas
    const query = wx.createSelectorQuery()
    query.select('#webgl')
      .fields({ node: true, size: true })
      .exec((res) => {
        console.log('Canvas查询结果:', res)
        
        // 添加错误检查
        if (!res || !res[0] || !res[0].node) {
          console.error('无法获取 canvas 节点!', res)
          return
        }
        
        const canvas = res[0].node
        console.log('Canvas节点获取成功')
        
        // 创建一个与canvas绑定的three.js
        const THREE = createScopedThreejs(canvas)
        
        this.setData({
          isRolling: false,
          diceValue1: null,
          diceValue2: null,
          diceSum: null
        })
        
        const info = wx.getSystemInfoSync()
        canvas.width = info.windowWidth
        canvas.height = info.windowHeight
        
        // 初始化渲染器
        const renderer = new THREE.WebGLRenderer({ 
          canvas, 
          antialias: true,
          alpha: true 
        })
        renderer.setSize(canvas.width, canvas.height)
        renderer.setClearColor(0x000000, 0)
        
        // 创建场景
        const scene = new THREE.Scene()
        
        // 创建相机
        const camera = new THREE.PerspectiveCamera(75, canvas.width / canvas.height, 0.1, 1000)
        camera.position.set(0, 0, 7) // 调整摄像机位置，以便能看到两个骰子
        camera.lookAt(0, 1.5, 0)  // 将视线中心点调整到两个骰子的中间位置
        
        // 添加光源
        const ambientLight = new THREE.AmbientLight(0xffffff, 0.5)
        scene.add(ambientLight)
        
        const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8)
        directionalLight.position.set(1, 1, 1)
        scene.add(directionalLight)
        
        // 创建八面体几何体和材质（可供两个骰子使用）
        const geometry = new THREE.OctahedronGeometry(1, 0)
        const material = new THREE.MeshPhongMaterial({
          color: 0x4169E1,
          flatShading: true
        })
        
        // 创建第一个八面体骰子（上方）
        const octahedron1 = new THREE.Mesh(geometry, material.clone())
        octahedron1.position.y = 2.5  // 从1.5调整为2.5，向上移动
        scene.add(octahedron1)
        
        // 创建第二个八面体骰子（下方）
        const octahedron2 = new THREE.Mesh(geometry, material.clone())
        octahedron2.material.color.set(0x6A5ACD) // 稍微不同颜色以区分
        octahedron2.position.y = 0.5  // 从-1.5调整为0.5，向上移动并减小与上方骰子的间距
        scene.add(octahedron2)
        
        // 设置模拟物理属性
        let rotationSpeed1 = { x: 0, y: 0, z: 0 }
        let rotationSpeed2 = { x: 0, y: 0, z: 0 }
        let gravity = 0.98
        let damping = 0.95
        let isRolling = false
        
        // 记录八面体的八个面的法向量，与八卦一一对应
        const faceNormals = [
          new THREE.Vector3(0, 1, 0),      // 乾 ☰
          new THREE.Vector3(0, -1, 0),     // 坤 ☷
          new THREE.Vector3(1, 0, 0),      // 震 ☳
          new THREE.Vector3(-1, 0, 0),     // 艮 ☶
          new THREE.Vector3(0, 0, 1),      // 离 ☲
          new THREE.Vector3(0, 0, -1),     // 坎 ☵
          new THREE.Vector3(1, 1, 1).normalize(),    // 兑 ☱
          new THREE.Vector3(-1, 1, 1).normalize()    // 巽 ☴
        ]
        
        // 骰子面值对应关系（1-8）
        const faceValues = [1, 2, 3, 4, 5, 6, 7, 8]
        
        // 摇动骰子函数
        this.rollDice = () => {
          if (isRolling) return
          
          isRolling = true
          this.setData({ isRolling: true })
          
          // 产生随机初始旋转速度 - 骰子1
          rotationSpeed1 = {
            x: (Math.random() - 0.5) * 0.3,
            y: (Math.random() - 0.5) * 0.3,
            z: (Math.random() - 0.5) * 0.3
          }
          
          // 产生随机初始旋转速度 - 骰子2
          rotationSpeed2 = {
            x: (Math.random() - 0.5) * 0.3,
            y: (Math.random() - 0.5) * 0.3,
            z: (Math.random() - 0.5) * 0.3
          }
        }
        
        // 修改骰子判断逻辑，确保上卦和下卦明确区分
        const getUpFace = (octahedron, isUpper) => {
          const worldUp = new THREE.Vector3(0, 0, 1) // Z轴朝上
          
          let maxDot = -Infinity
          let upFaceIndex = -1
          
          for (let i = 0; i < faceNormals.length; i++) {
            const normal = faceNormals[i].clone()
            normal.applyQuaternion(octahedron.quaternion)
            
            const dot = normal.dot(worldUp)
            if (dot > maxDot) {
              maxDot = dot
              upFaceIndex = i
            }
          }
          
          // 返回1-8的面值对应八卦序号
          return upFaceIndex + 1
        }
        
        // 动画循环
        const animate = () => {
          canvas.requestAnimationFrame(animate)
          
          if (isRolling) {
            // 应用旋转 - 骰子1
            octahedron1.rotation.x += rotationSpeed1.x
            octahedron1.rotation.y += rotationSpeed1.y
            octahedron1.rotation.z += rotationSpeed1.z
            
            // 应用旋转 - 骰子2
            octahedron2.rotation.x += rotationSpeed2.x
            octahedron2.rotation.y += rotationSpeed2.y
            octahedron2.rotation.z += rotationSpeed2.z
            
            // 应用阻尼 - 骰子1
            rotationSpeed1.x *= damping
            rotationSpeed1.y *= damping
            rotationSpeed1.z *= damping
            
            // 应用阻尼 - 骰子2
            rotationSpeed2.x *= damping
            rotationSpeed2.y *= damping
            rotationSpeed2.z *= damping
            
            // 检查是否停止滚动
            if (
              Math.abs(rotationSpeed1.x) < 0.001 &&
              Math.abs(rotationSpeed1.y) < 0.001 &&
              Math.abs(rotationSpeed1.z) < 0.001 &&
              Math.abs(rotationSpeed2.x) < 0.001 &&
              Math.abs(rotationSpeed2.y) < 0.001 &&
              Math.abs(rotationSpeed2.z) < 0.001
            ) {
              isRolling = false
              
              // 明确指定上卦和下卦
              const upFace1 = getUpFace(octahedron1, true)  // 上卦
              const upFace2 = getUpFace(octahedron2, false) // 下卦
              
              // 获取对应的六十四卦名称
              const fullGuaName = this.getFullGuaName(upFace1, upFace2)
              
              this.setData({
                isRolling: false,
                diceValue1: upFace1,
                diceValue2: upFace2,
                fullGuaName: fullGuaName
              })
            }
          }
          
          renderer.render(scene, camera)
        }
        
        animate()
        
        // 添加触摸事件
        this.bindTouchEvents(canvas)
      })
  },
  
  bindTouchEvents(canvas) {
    let lastTouchY = 0
    let lastTouchX = 0
    
    // 触摸开始
    canvas.addEventListener('touchstart', (e) => {
      lastTouchX = e.touches[0].clientX
      lastTouchY = e.touches[0].clientY
    })
    
    // 触摸移动（摇动）
    canvas.addEventListener('touchmove', (e) => {
      const touchX = e.touches[0].clientX
      const touchY = e.touches[0].clientY
      
      // 计算移动速度
      const deltaX = touchX - lastTouchX
      const deltaY = touchY - lastTouchY
      
      // 如果移动足够快，则触发骰子滚动
      if (Math.abs(deltaX) > 10 || Math.abs(deltaY) > 10) {
        this.rollDice()
      }
      
      lastTouchX = touchX
      lastTouchY = touchY
    })
  },
  
  // 手动触发骰子滚动的按钮事件处理函数
  onRollDice() {
    if (this.rollDice) {
      this.rollDice()
    }
  },
  
  onTouchStart(e) {
    console.log('触摸开始', e)
    if (this.lastTouchX === undefined) {
      this.lastTouchX = e.touches[0].clientX
      this.lastTouchY = e.touches[0].clientY
    }
  },
  
  onTouchMove(e) {
    console.log('触摸移动', e)
    const touchX = e.touches[0].clientX
    const touchY = e.touches[0].clientY
    
    // 计算移动速度
    const deltaX = touchX - (this.lastTouchX || touchX)
    const deltaY = touchY - (this.lastTouchY || touchY)
    
    // 如果移动足够快，则触发骰子滚动
    if (Math.abs(deltaX) > 10 || Math.abs(deltaY) > 10) {
      if (this.rollDice) {
        this.rollDice()
      }
    }
    
    this.lastTouchX = touchX
    this.lastTouchY = touchY
  },
  
  // 添加获取六十四卦名称的方法
  getFullGuaName(upperGua, lowerGua) {
    // 六十四卦名称的二维数组映射 [上卦索引][下卦索引]
    const sixtyFourGua = [
      ['乾为天', '天风姤', '天山遁', '天地否', '风天小畜', '山天大畜', '火天大有', '天水讼'],
      ['地天泰', '坤为地', '地雷复', '地泽临', '雷地豫', '泽地萃', '火地晋', '地水师'],
      ['雷天大壮', '山雷颐', '震为雷', '雷泽归妹', '山雷遁', '泽雷随', '火雷噬嗑', '雷水解'],
      ['水天需', '泽天夬', '泽雷屯', '艮为山', '水山蹇', '泽山咸', '火山旅', '山水蒙'],
      ['火天同人', '火地明夷', '火雷噬嗑', '火山旅', '离为火', '火风鼎', '火水未济', '火泽睽'],
      ['水天需', '水地比', '水雷屯', '水山蹇', '水火既济', '坎为水', '水风井', '水泽节'],
      ['风天小畜', '风地观', '风雷益', '风山渐', '风火家人', '风水涣', '兑为泽', '风泽中孚'],
      ['天水讼', '地水师', '雷水解', '山水蒙', '火水未济', '水泽节', '泽水困', '巽为风']
    ]
    
    // 返回对应的卦名
    return sixtyFourGua[upperGua-1][lowerGua-1]
  }
}) 